import { create } from 'zustand'
import { createJSONStorage, persist } from 'zustand/middleware'

import type { ModList, GameItem, GameList } from '@/types/game'

type GameModList = {
  [key: string]: ModList
}

type GameModListStore = {
  gameModList: GameModList
  setGameModList: (gameId: string, modList: ModList) => void
  getGameModList: (gameId: string) => ModList
}

const useGameModListStore = create<GameModListStore>()(
  persist(
    (set, get) => ({
      gameModList: {},
      setGameModList: (gameId: string, modList: ModList) => {
        set((state) => ({
          gameModList: {
            ...state.gameModList,
            [gameId]: modList,
          }
        }))
      },
      getGameModList: (gameId: string) => {
        return get().gameModList[gameId]
      }
    }),
    {
      name: 'game-mod-list',
      storage: createJSONStorage(() => localStorage),
    }
  )
)

type GameListStore = {
  activeGame: GameItem | undefined
  gameList: GameList
  setActiveGame: (game: GameItem) => void
  setGameList: (gameList: GameList) => void
}

const useGameListStore = create<GameListStore>()(
  persist(
    (set) => ({
      activeGame: undefined,
      gameList: [],
      setActiveGame: (game: GameItem) => {
        set(() => ({
          activeGame: game
        }))
      },
      setGameList: (gameList: GameList) => {
        set(() => ({
          gameList
        }))
      },
    }),
    {
      name: 'game-list',
      storage: createJSONStorage(() => localStorage),
    }
  )
)

export {
  useGameModListStore,
  useGameListStore,
}